package controllers;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.HashSet;

import keeperproperties.KeeperProperties;

import org.apache.log4j.Logger;

import annotation.PropertyAnnotation;

public class Controller {
	private static KeeperProperties keeper_properties = KeeperProperties
			.getInstance();
	private static PropertyAnnotation annotation;
	private static HashMap<String, String> propertiesMap = new HashMap<String, String>();
	private static HashSet<String> listValuesProperties = new HashSet<String>();
	private static final String ERROR = "Exception by annotation";
	private static Logger log = Logger.getLogger(Controller.class);

	public static void setPropertyByAnnotation(Object o) {
		try {
			propertiesMap.putAll(keeper_properties.getProperties());
			listValuesProperties.addAll(propertiesMap.keySet());
			Field[] fields = o.getClass().getDeclaredFields();
			for (Field f : fields) {
				if (f.getDeclaredAnnotations()!=null) {
					Annotation[] anno = f.getDeclaredAnnotations();
					for (Annotation a : anno) {
						if (a.annotationType().equals(PropertyAnnotation.class)) {
							annotation = (PropertyAnnotation) a;
							String nameField = annotation.getConfigName()
									.toString();
							for (String nameProperty : listValuesProperties) {
								if (nameField.equals(nameProperty)) {
									String propertiesValue = propertiesMap
											.get(nameProperty);
									f.setAccessible(true);
									f.set(o, propertiesValue);
								}
							}
						}
					}

				}
			}
		} catch (Exception e) {
			log.error(ERROR);
		}
	}

}
